package com.jiazhong.basic.pack0724;

import lombok.SneakyThrows;

import java.io.File;
import java.io.FileReader;
import java.io.Reader;

// 字符流的读取
public class DemoD {

    @SneakyThrows
    private static void a() {
        File file = new File("/Users/dailyblue/workspace/io/1.txt");
        if (!file.exists()) {
            System.out.println("文件不存在");
            return;
        }
        if (!file.isFile()) {
            System.out.println("不是一个文件");
            return;
        }
        // 产生一个字符读取流
        Reader reader = new FileReader(file);
        // 读取一个字符
        int i = reader.read();
        if (i == -1) {
            System.out.println("文件读取完毕");
            return;
        }
        char ch = (char) i;
        System.out.println(ch);
        reader.close();

    }

    @SneakyThrows
    private static void b() {
        File file = new File("/Users/dailyblue/workspace/io/1.txt");
        if (!file.exists()) {
            System.out.println("文件不存在");
            return;
        }
        if (!file.isFile()) {
            System.out.println("不是一个文件");
            return;
        }
        // 产生一个字符读取流
        Reader reader = new FileReader(file);
        while (true) {
            // 读取一个字符
            int i = reader.read();
            if (i == -1) {
                System.out.println("文件读取完毕");
                break;
            }
            char ch = (char) i;
            System.out.print(ch);
        }
        reader.close();

    }

    @SneakyThrows
    private static void c() {
        File file = new File("/Users/dailyblue/workspace/io/1.txt");
        if (!file.exists()) {
            System.out.println("文件不存在");
            return;
        }
        if (!file.isFile()) {
            System.out.println("不是一个文件");
            return;
        }
        Reader reader = new FileReader(file);
        char[] chars = new char[5];
        int len = reader.read(chars);
        System.out.println(chars);
        reader.close();
    }

    @SneakyThrows
    private static void d() {
        File file = new File("/Users/dailyblue/workspace/io/1.txt");
        if (!file.exists()) {
            System.out.println("文件不存在");
            return;
        }
        if (!file.isFile()) {
            System.out.println("不是一个文件");
            return;
        }
        Reader reader = new FileReader(file);
        char[] chars = new char[5];
        while (true) {
            int len = reader.read(chars);
            if(len == -1) {
                break;
            }
            String str = new String(chars, 0, len);
            System.out.print(str);
        }
        reader.close();
    }

    public static void main(String[] args) {
        d();
    }
}
